<!-- 元数据编辑对话框 -->
<template>
  <CommonDialog v-model="visible" :loading="loading" :title="`${metadataId ? '编辑' : '创建'}`" :width="500"
    @submit="submit" @cancel="cancel">
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="80">
      <FormItem label="标题" prop="name">
        <Input v-model="formData.name" placeholder="请输入标题"></Input>
      </FormItem>

      <FormItem label="访问别称" prop="code">
        <Input v-model="formData.code" placeholder="请输入访问别称"></Input>
      </FormItem>

      <FormItem v-if="esShow" label="选项">
        <Checkbox v-model="formData.fromdb">ES数据</Checkbox>
      </FormItem>

      <template v-if="formData.fromdb">
        <FormItem v-for="(value,key) in optionsMap" :key="key" :label="value.label" :prop="key">
          <Select v-model="formData[key]" transfer :placeholder="`请选择${value.label}`">
            <Option v-for="item in value.options" :value="item.id" :key="item.id">
              {{item.name}}
            </Option>
          </Select>
        </FormItem>
      </template>

      <FormItem label="备注">
        <Input v-model="formData.eventname" type="textarea" placeholder="请输入备注" :rows="4"></Input>
      </FormItem>
      
    </Form>
  </CommonDialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Message } from 'view-ui-plus'

import { metadata } from '@/api/modules/modelSetting'
import { sysdicGetByCode } from '@/api/modules/role'
import OptionForm from '@/components/OptionForm/index.vue'
import CommonDialog from '@/components/CommonDialog/index.vue'

const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)
const esShow = ref(false)
// 表单元素ref
const formRef = ref(null)

// 元数据ID
const metadataId = ref(undefined)

// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  name: '',
  code: '',
  fromdb: false,
  eventname: '',
  listblocktemplet: '',
  previewtemplet: ''
})

// 表单校验条件
const rules = ref({
  username: [{ required: true, message: '请填写用户名称', trigger: 'blur' }]
})

const optionsMap = ref({
  listblocktemplet: {
    label: 'ES资源',
    code: 'com.dic.es.type',
    options: []
  },
  previewtemplet: {
    label: 'JAVABean',
    code: 'com.dic.db.type',
    options: []
  }
})

const getSelectData = () => {
  Object.entries(optionsMap.value).forEach(([key, item]) => {
    sysdicGetByCode({
      data: {
        code: item.code
      }
    }).then(({data}) => {
      // 将数据转换为OptionForm组件需要的格式
      item.options = data
    })
  })
}

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    await metadata.edit({
      data: {
        ...formData.value,
        id: metadataId.value
      }
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const getDetailData = () => {
  loading.value = true

  metadata
    .detail({
      data: {
        id: metadataId.value
      }
    })
    .then(({ data }) => {
      for (const key in formData.value) {
        if (key === 'password') continue

        formData.value[key] = data[key]
      }

      esShow.value = data.datasql

      if(esShow.value) {
        getSelectData()
      }
    }).finally(()=>{
      loading.value = false
    })
}

/**
 * 初始化对话框
 */
const initDialog = id => {
  // 显示对话框
  visible.value = true

  metadataId.value = id

  if (id) {
    getDetailData()
  }
}

defineExpose({
  initDialog
})
</script>